<?php
    require_once($_SERVER['DOCUMENT_ROOT'] . "/AppSaleOnline/libs/model.php"); // hien thi thu muc goc

    // require_once("../libs/model.php");
    // echo getcwd();
    // echo getcwd();
    class User extends Model{
        // constructor of User class
        public function __construct()
        {
            parent::__construct();
        }
        // get user list from database appstore
        public function getALlUser()
        {
            $sql = "Select * From users order by user_id DESC";
            $result = mysqli_query($this->_link, $sql);
            if($result == ""){
                die("Query error: ".mysqli_error($this->_link));
            } else {
                $data = array();
                while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
                {
                    $data[] = $rows;
                }
                return $data;
            }
        }
        public function get_id_with_username($username)
        {
            $sql = "SELECT `user_id` FROM `users` WHERE `username` = '$username'";
            
            $result = mysqli_query($this->_link, $sql);
            
            if(mysqli_num_rows($result) > 0)
            {
                return mysqli_fetch_row($result);
            }
        }
        // checkLoginUser function
        public function checkLoginUser($username, $password)
        {
            
            $username = mysql_real_escape_string($username); // tranh sql injection
            $password = md5($password);// ma hoa password sang md5

            $sql = "SELECT * FROM users WHERE username='$username' AND password='$password'";
            // var_dump($sql);
            $result = mysqli_query($this->_link,$sql);
            if($result == "")
            {
                die("Query error:".mysqli_error($this->_link));
            }else{
                $numrows = mysqli_num_rows($result);
                if($numrows > 0)
                    return true;
                else
                    return false;
            }
        }

        public function get_image_from_username($user_name)
        {
            $sql = "Select `user_image` from users WHERE `username` = '$user_name'";

            $result = mysqli_query($this->_link, $sql);
            if($result != "")
                return mysqli_fetch_row($result)[0];
            else 
                return ""; // khong co image nao tra ve
        }

        // getUserRole function user define
        public function getUserRole_With_userId($user_id)
        {
            $sql = "SELECT user_role FROM users WHERE user_id = $user_id";

            $result = mysqli_query($this->_link, $sql);

            if($result == "")
            {
                die("Query error: ".mysqli_error($this->_link));
            }else{
                $role = mysqli_fetch_row($result);
                return $role[0];
            }
        }
        // lay quyen cua user
        public function getUserRole($user_name)
        {
            $sql = "SELECT user_role FROM users WHERE username = '$user_name'";

            $result = mysqli_query($this->_link, $sql);

            if($result == "")
            {
                die("Query error: ".mysqli_error($this->_link));
            }else{
                $role = mysqli_fetch_row($result);
                return $role[0];
            }
        }
        // function get userInfo
		public function getUserInfo($username)
		{
			$sql = "SELECT * FROM users WHERE username= '$username'";
			$result = mysqli_query($this->_link, $sql);
			if(!$result){
				throw new Exception("Error ".mysqli_error($this->_link));
			}
			try{
				$acc_info = array();
				while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
				{
					$acc_info[] = $rows;
				}
				return $acc_info;
			}catch(Exception $e){
				return $e->getMessage();
			}
		}

        // lay thong tin tai khoan voi user_id nhap vao
        public function get_account_information($user_id)
        {
            $sql = "SELECT * FROM users WHERE user_id = $user_id";
            $result = mysqli_query($this->_link, $sql);
            
            if(empty($result)){
                
                throw new Exception("Error ".mysqli_error($this->_link));
                
            }try{
                $acc_information = array();

                while($rows  = mysqli_fetch_array($result, MYSQL_ASSOC))
                {
                    $acc_information[] = $rows;
                }
                
                return $acc_information;
                
            }catch(Exception $e){
                return $e->getMessage();
            }
        }

        // sửa thông tin của người dùng
        public function edit_account_information($user_id, $username, $address, $sex, $telephone, $email)
        {
            // thiet lập lại các biến
            $user_id   = mysql_real_escape_string($user_id); // user_id
            $username  = mysql_real_escape_string($username); // username
            $address   = mysql_real_escape_String($address); // address
            $sex       = mysql_real_escape_string($sex); // gender
            $telephone = mysql_real_escape_string($telephone); // telephone
            $email     = mysql_real_escape_string($email);

            // truy vấn SQL
            $sql = "UPDATE  users SET `username` =  '$username', `user_address` ='$address',`user_sex` = '$sex', `user_telephone` ='$telephone', `user_email` = '$email'
                    WHERE `user_id` = $user_id";

            // ket qua tra ve cau truy van
            $result = mysqli_query($this->_link, $sql);

            // kiem tra ket qua rong
            if(empty($result)){
                throw new Exception("Error ".mysqli_error($this->_link));
            }
            try{
                return true; // neu khong thoa man truong hop empty thi tra ve true
            }catch(Exception $e){
                return $e->getMessage();
            }
        }

        // Xóa một user với ID của user đó
        public function delete_user_with_id($id)
        {
            $sql = "Delete from users WHERE user_id = $id";

            $result = mysqli_query($this->_link, $sql);

            if($result != "" || $result != null) {
                return true;
            } else {
                return false;
            }
        }

        // insert ban ghi vao CSDL
        public function insert_user_into_db($username, $password, $role, $address, $gender, $telephone, $email, $image)
        {
            // thiet lap lai cac bien
            $username  = mysql_real_escape_string($username);
            $password  = md5(mysql_real_escape_string($password));
            $role      = mysql_real_escape_string($role);
            $address   = mysql_real_escape_string($address);
            $gender    = mysql_real_escape_string($gender);
            $telephone = mysql_real_escape_string($telephone);
            $email     = mysql_real_escape_string($email);
            $image     = mysql_real_escape_string($image);

            $sql = "INSERT  INTO users(`username`, `password`, `user_role`, `user_address`, `user_sex`, `user_telephone`, `user_email`, `user_image`)
            VALUES('$username', '$password', '$role','$address', b'$gender', '$telephone', '$email', '$image')" or die(mysqli_error($this->_link));

            // var_dump($sql);exit();

            $result = mysqli_query($this->_link, $sql);

            if($result != null)
                return true;
            return false;
        }

        // kiem tra password user nhap vao co ton tai hay khong
        public function check_password_user($username, $password)
        {
            $sql = "Select `password` From  `users` WHERE `username` = '$username'";
            $result = mysqli_query($this->_link, $sql);

            if($result != "")
            {
                if(mysqli_fetch_row($result)[0] == md5($password))
                    return true;
                else
                    return false;
            }
        }

        // change password
        public function change_password_by_username($oldPass, $username, $newPass)
        {
            // var_dump($this->check_password_user($username, $oldPass));

            if($this->check_password_user($username, $oldPass) == true)
            {
                $sql = "UPDATE users SET `password` = md5('$newPass') WHERE `username` = '$username' ";

                $result = mysqli_query($this->_link, $sql);

                if($result == "") return false;
                return true;
            }

        }

        // chuc nang tim kiem user theo địa chỉ và tên
        public function search_user_by_address_and_name($keyword, $address)
        {
            if($keyword == "") {
                $sql = "SELECT * From users WHERE `user_address` LIKE '%$address%'";
            }
            elseif($address == "")
            {
                $sql = "SELECT * From users WHERE `username` LIKE '%$keyword%'";
            }
            else
                $sql = "SELECT * From users WHERE `user_address` LIKE '%$address%' OR `username` LIKE '%$keyword%'";

            // var_dump($sql);
            $result = mysqli_query($this->_link, $sql);

            if($result != "")
            {
                $data = array();
                while($rows = mysqli_fetch_array($result, MYSQLI_ASSOC))
                {
                    $data[] = $rows;
                }
                return $data;
            }
        }
    }
?>